package com.vimi8.ebb.auth.api;

import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.auth.dto.AuthUserDto;
import com.vimi8.ebb.auth.model.Error;
import com.vimi8.ebb.auth.model.Paginator;
import com.vimi8.ebb.auth.model.UserOrg;
import com.vimi8.ebb.auth.service.DBClientDetailsService;
import com.vimi8.ebb.auth.service.GeoCodingsService;
import com.vimi8.ebb.auth.service.OrganizationService;
import com.vimi8.ebb.auth.service.UserAuthorityService;
import com.vimi8.ebb.auth.utils.CommonUtil;
import com.vimi8.ebb.auth.utils.PagesUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * Created by think on 2016/12/15.
 */
@RestController
public class EmployeeController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private GeoCodingsService geoCodingsService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private DBClientDetailsService dbClientDetailsService;
    @Autowired
    private UserAuthorityService userAuthorityService;

    @ApiOperation(value = "APP-查询员工和股东列表信息",notes = "查询员工、股东信息",response = AuthUserDto.class,tags = {"员工相关信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = AuthUserDto.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = AuthUserDto.class) })
    @RequestMapping(value = "/dept/emp/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<AuthUserDto>>> EmployeeInfoGET(
            @ApiParam(value = "员工姓名",required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "是否贫困户(1:贫困户，0：非贫困户)",required = false) @RequestParam(required = false) String isPoor,
            @ApiParam(value = "是否是所有的股东(1:是，0：所有的员工（包括既是员工也是股东的job）)",required = false) @RequestParam(required = false) String isShareholder,
                @ApiParam(value = "状态（0：在职，1：冻结）",required = false) @RequestParam(required = false) String status,
            @ApiParam(value = "工种（org_manager:管理员,  org_shareholder：股东，org_senior_manager:高级管理员，org_shareholder_manager： 既是管理员又是股东，org_shareholder_senior_manager：既是股东又是高级管理员, org_emp:组织里面的员工）",required = false) @RequestParam(required = false) String job,
            @ApiParam(value = "开始页",required = true) @RequestParam(required = true) int start,
            @ApiParam(value = "页面大小",required = true) @RequestParam(required = true) int size
    ){
        String clientId = OAuth2AuthenticationImpl.clientId();
        int totalCount=0;
        String isShakePoverty=null;
        logger.info("isPoor="+isPoor);
        if(!StringUtils.isEmpty(isPoor)){
            isShakePoverty="0".equals(isPoor)?"1":"0";
        }
        if(StringUtils.isEmpty(isShareholder)||"0".equals(isShareholder)){
            isShareholder=null;
        }
        logger.info("isShakePoverty="+isShakePoverty);
        if("1".equals(isShareholder)){
            totalCount = organizationService.getAuthUserCountForHolder(clientId,job,name,status,isShakePoverty);
        }else{
            totalCount= organizationService.getAuthUserCountForEmp(clientId,job,name,status,isShakePoverty);
        }
        PagesUtil pagesUtil = new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setTotalCount(totalCount);
        pagesUtil.setCurrentPage(start);
        if (start < 1) {
            pagesUtil.setCurrentPage(1);
        }
        List<AuthUserDto> authUsers= null;
        if("1".equals(isShareholder)){
            authUsers = organizationService.getAuthUserForHolder(clientId,
                    job,name,status,isShakePoverty,pagesUtil.getStartPage(),size);
        }else{

            authUsers = organizationService.getAuthUserForEmp(clientId,
                    job,name,status,isShakePoverty,pagesUtil.getStartPage(),size);
        }
        for (AuthUserDto authUserDto : authUsers) {
            authUserDto.setAddressCode(getAllAddress(authUserDto.getAddressCode()));
        }
        Paginator<List<AuthUserDto>> paginators = new Paginator<List<AuthUserDto>>(pagesUtil.getCurrentPage(), pagesUtil.getPageSize(), pagesUtil.getTotalPage(),
                pagesUtil.getTotalCount(), authUsers);

        return new HttpResponseEntity<Paginator<List<AuthUserDto>>>(paginators, HttpStatus.OK);

    }



//    @ApiOperation(value = "APP-查询员工、股东记录数",notes = "查询员工、股东记录数",response = EmployeeCountDTO.class,tags = {"员工相关信息"})
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "成功,返回影响行数", response = EmployeeCountDTO.class),
//            @ApiResponse(code = 500, message = "失败,返回消息", response = EmployeeCountDTO.class) })
//    @RequestMapping(value = "/dept/emp/count",method = RequestMethod.GET)
//    public HttpResponseEntity<EmployeeCountDTO> EmployeeCountGET(
//            @ApiParam(value = "组织id",required = false) @RequestParam(required = false) String orgId
//    ){
//
//        return null;
//    }
//
//
//
//    @ApiOperation(value = "APP-添加员工或者股东",notes = "组织法人添加员工信息",response = String.class,tags = {"员工相关信息"})
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
//            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
//    @RequestMapping(value = "/dept/emp/",method = RequestMethod.POST)
//    public HttpResponseEntity<String> EmployeeInfoPOST(
//            @ApiParam(value = "组织id",required = true) @RequestParam(value = "orgId",required = false) String orgId,
//            @ApiParam(value = "员工id", required = true) @RequestParam(value = "openId", required = true) String openId
//    ){
//
//        return null;
//    }

    @ApiOperation(value = "APP-删除组织中某个员工信息", notes = "根据客组织id和员工id解除组织和员工所属关系信息", response = String.class, authorizations = {
            @Authorization(value = "accessCode", scopes = {
                    @AuthorizationScope(scope = "write:auth-server:user:me", description = "资源auth-server下个人用户信息的写入权限.")
            })
    }, tags={ "员工相关信息", })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/dept/emp/",
            method = RequestMethod.PUT)
    HttpResponseEntity<String> orgDeptEmpDelete(
            @ApiParam(value = "userId",required = true) @RequestParam(value = "userId",required = true) String userId,
            @ApiParam(value = "工种（org_manager:管理员,  org_shareholder：只是股东，不是员工， org_shareholder_emp：既是股东又是员工，org_senior_manager:高级管理员，org_shareholder_manager： 既是管理员又是股东，org_shareholder_senior_manager：既是股东又是高级管理员, org_emp:组织里面的员工）",required = true) @RequestParam(value = "job",required = true) String job

    ){

        int count = 0;

        try {
            //获取openId
            String orgId = OAuth2AuthenticationImpl.clientId();
            count = dbClientDetailsService.deleteEmployee(userId,orgId);
            count+=  organizationService.deleteOrganizationEmp(orgId,userId,job);

            //查询出其他组织 将删除的用户设置一个当前的cientid
            UserOrg userOrg = userAuthorityService.getUserOrgByUserid(userId);
            if(userOrg==null){
                count+=userAuthorityService.updateUserDefaultClientIdByUserId(userId,"personal");
            }

            count+=userAuthorityService.updateUserDefaultClientIdByUserId(userId,userOrg.getClientId());
//            String scopes=null;
//            scopes=  userAuthorityService.getScopesByUserId(orgId,userId);
//            if("org_emp".equals(job)){
//                if(!StringUtils.isEmpty(scopes)&&scopes.contains("user-me|")){
//                    scopes=scopes.replace("user-me|","");
//                    userAuthorityService.updateScopesByUserId(orgId,userId,scopes);
//                }
//            }else if("org_shareholder".equals(job)){
//                if(!StringUtils.isEmpty(scopes)&&scopes.contains("shareholder|")){
//                    scopes=scopes.replace("shareholder|","");
//                    userAuthorityService.updateScopesByUserId(orgId,userId,scopes);
//                }
//            }
            // user-me|user|shareholder|admin|senior-admin|super-admin


        }catch (Exception e){
            return new HttpResponseEntity<String>(new Error().error("sql_error").errorDescription(e.
                    getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }


        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }



    @ApiOperation(value = "APP-冻结员工股东",notes = "冻结员工股东",response = String.class,tags = {"员工相关信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/dept/emp/freezes/",method = RequestMethod.PUT)
    public HttpResponseEntity<String> EmployeeInfoPUT(
            @ApiParam(value = "openId",required = true) @RequestParam(value = "openId",required = true) String openId,
            @ApiParam(value = "freezesStatus(1表示冻结，0表示解冻)",required = true) @RequestParam(value = "freezesStatus",required = true) String freezesStatus
    ){

        int count = 0;

        try {
            //获取openId
            String orgId = OAuth2AuthenticationImpl.clientId();
            if(StringUtils.isEmpty(freezesStatus)){
                freezesStatus="0";
            }
            freezesStatus="1".equals(freezesStatus)?freezesStatus:"0";
            count = dbClientDetailsService.freezeEmployee(openId,orgId,freezesStatus);
        }catch (Exception e){
            return new HttpResponseEntity<String>(new Error().error("sql_error").
                    errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }


        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }


    private String getAllAddress(String addressCode) {
        String farmAdress = "";
        if (StringUtils.isEmpty(addressCode)) {
            return null;
        }
        Map<String, String> geoCodingsMap = null;
        try {
            geoCodingsMap = CommonUtil.parseGeoCodings(addressCode);
        } catch (Exception e) {
            return null;
        }

        String city = geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city")) == null ? "" : geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city")).getGeoName();
        String county = geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county")) == null ? "" : geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county")).getGeoName();
        String vilage = geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage")) == null ? "" : geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage")).getGeoName();
        String burg = geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg")) == null ? "" : geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg")).getGeoName();
        if (!StringUtils.isEmpty(city)) {
            farmAdress += city;
        }
        if (!StringUtils.isEmpty(county)) {
            farmAdress += county;
        }
        if (!StringUtils.isEmpty(vilage)) {
            farmAdress += vilage;
        }
        if (!StringUtils.isEmpty(burg)) {
            farmAdress += burg;
        }
        return farmAdress;
    }



}


